<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket聊天测试</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stomp-websocket@2.3.4-next/lib/stomp.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .chat-container {
            border: 1px solid #ccc;
            padding: 20px;
            height: 400px;
            overflow-y: auto;
            margin-bottom: 20px;
        }
        .message {
            margin-bottom: 10px;
            padding: 10px;
            border-radius: 5px;
        }
        .sent {
            background-color: #e3f2fd;
            margin-left: 50px;
        }
        .received {
            background-color: #f1f1f1;
            margin-right: 50px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
        }
        input, textarea, button {
            padding: 8px;
            width: 100%;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>
    <h1>WebSocket聊天测试</h1>
    
    <div id="login-form">
        <div class="form-group">
            <label for="username">用户名:</label>
            <input type="text" id="username" placeholder="输入用户名">
        </div>
        <div class="form-group">
            <label for="password">密码:</label>
            <input type="password" id="password" placeholder="输入密码">
        </div>
        <button id="connect-btn">登录并连接</button>
    </div>
    
    <div id="chat-form" style="display: none;">
        <p id="connection-status">未连接</p>
        <div class="form-group">
            <label for="receiver-id">接收者ID:</label>
            <input type="text" id="receiver-id" placeholder="输入接收者ID">
        </div>
        <div class="chat-container" id="chat-messages"></div>
        <div class="form-group">
            <label for="message">消息:</label>
            <textarea id="message" placeholder="输入消息"></textarea>
        </div>
        <button id="send-btn">发送</button>
        <button id="disconnect-btn">断开连接</button>
    </div>
    
    <script>
        let stompClient = null;
        let token = null;
        let currentUserId = null;
        
        // 登录并连接WebSocket
        document.getElementById('connect-btn').addEventListener('click', function() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            if (!username || !password) {
                alert('请输入用户名和密码');
                return;
            }
            
            // 登录获取token
            fetch('/user/getUserById', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    userName: username,
                    passworld: password
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    // 登录成功，获取token和用户ID
                    token = data.data.token;
                    currentUserId = data.data.userId;
                    
                    // 连接WebSocket
                    connectWebSocket();
                    
                    // 显示聊天界面
                    document.getElementById('login-form').style.display = 'none';
                    document.getElementById('chat-form').style.display = 'block';
                } else {
                    alert('登录失败: ' + data.msg);
                }
            })
            .catch(error => {
                console.error('登录错误:', error);
                alert('登录出错，请检查控制台');
            });
        });
        
        // 连接WebSocket
        function connectWebSocket() {
            const socket = new SockJS('/ws');
            stompClient = Stomp.over(socket);
            
            stompClient.connect(
                { token: token },
                function(frame) {
                    console.log('已连接: ' + frame);
                    document.getElementById('connection-status').textContent = '已连接';
                    
                    // 订阅个人消息
                    stompClient.subscribe('/user/queue/messages', onMessageReceived);
                    
                    // 订阅已读回执
                    stompClient.subscribe('/user/queue/read-receipts', onReadReceiptReceived);
                    
                    // 发送用户加入消息
                    stompClient.send("/app/chat.addUser",
                        { token: token },
                        JSON.stringify({ type: 'JOIN' })
                    );
                },
                function(error) {
                    console.error('连接错误:', error);
                    document.getElementById('connection-status').textContent = '连接失败';
                }
            );
        }
        
        // 断开连接
        document.getElementById('disconnect-btn').addEventListener('click', function() {
            if (stompClient !== null) {
                stompClient.disconnect();
                document.getElementById('connection-status').textContent = '已断开连接';
                
                // 显示登录界面
                document.getElementById('login-form').style.display = 'block';
                document.getElementById('chat-form').style.display = 'none';
            }
        });
        
        // 发送消息
        document.getElementById('send-btn').addEventListener('click', function() {
            const receiverId = document.getElementById('receiver-id').value;
            const messageContent = document.getElementById('message').value;
            
            if (!receiverId || !messageContent) {
                alert('请输入接收者ID和消息内容');
                return;
            }
            
            if (stompClient) {
                const chatMessage = {
                    type: 'CHAT',
                    receiverId: receiverId,
                    content: messageContent,
                    isGroup: false
                };
                
                stompClient.send("/app/chat.sendMessage",
                    { token: token },
                    JSON.stringify(chatMessage)
                );
                
                // 显示发送的消息
                addMessageToChat(currentUserId, messageContent, true);
                
                // 清空消息输入框
                document.getElementById('message').value = '';
            } else {
                alert('未连接到服务器');
            }
        });
        
        // 接收消息
        function onMessageReceived(payload) {
            const message = JSON.parse(payload.body);
            console.log('收到消息:', message);
            
            // 如果是聊天消息，显示在聊天窗口
            if (message.type === 'CHAT') {
                const isSent = message.senderId == currentUserId;
                addMessageToChat(message.senderId, message.content, isSent);
                
                // 如果是收到的消息，发送已读回执
                if (!isSent) {
                    sendReadReceipt(message.senderId);
                }
            }
        }
        
        // 接收已读回执
        function onReadReceiptReceived(payload) {
            const receipt = JSON.parse(payload.body);
            console.log('收到已读回执:', receipt);
            
            // 可以在这里更新消息的已读状态
        }
        
        // 发送已读回执
        function sendReadReceipt(senderId) {
            if (stompClient) {
                const readReceipt = {
                    type: 'READ',
                    senderId: senderId
                };
                
                stompClient.send("/app/chat.markRead",
                    { token: token },
                    JSON.stringify(readReceipt)
                );
            }
        }
        
        // 添加消息到聊天窗口
        function addMessageToChat(senderId, content, isSent) {
            const chatMessages = document.getElementById('chat-messages');
            const messageElement = document.createElement('div');
            
            messageElement.classList.add('message');
            messageElement.classList.add(isSent ? 'sent' : 'received');
            
            const senderText = isSent ? '我' : '用户 ' + senderId;
            messageElement.textContent = senderText + ': ' + content;
            
            chatMessages.appendChild(messageElement);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
    </script>
</body>
</html>